<template>
  <div class="userlook-box">
    <el-card>
      <el-tabs>
        <el-tab-pane label="登录账户设置">
          <el-form
            ref="form"
            class="form"
            label-width="100px"
            :model="form"
            :rules="rules"
          >
            <el-form-item label="姓名" prop="username">
              <el-input v-model="form.username" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" show-password />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submmit">更新</el-button>
              <el-button @click="$router.push('/employees')">取消</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="个人详情" lazy>
          <Info :user-info="propUserInfo" @updataUserInfo="updataUserInfo" />
        </el-tab-pane>
        <el-tab-pane label="岗位信息" lazy>
          <Job />
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import { sysUser, sysUserEdit } from '@/api/user'
export default {
  // 异步组件：即点击该tab的的时候才渲染组件
  components: {
    Info: () => import('./components/info.vue'),
    Job: () => import('./components/Job.vue')
  },
  data() {
    return {
      propUserInfo: {},
      userInfo: {},
      userId: this.$route.params.id,
      form: {
        username: '',
        password: ''
      },
      rules: {
        username: [{ required: true, message: '必填', trigger: 'change' }],
        password: [
          { required: true, message: '必填', trigger: 'change' },
          { min: 6, max: 12, message: '6-12位' }
        ]
      }
    }
  },
  created() {
    this.getData()
  },
  methods: {
    // 获取用户基本信息
    async getData() {
      const res = await sysUser(this.userId)
      // 将数据保存起来
      this.userInfo = res.data
      // 中断组件内的个人详情与当前组件的关联
      this.propUserInfo = JSON.parse(JSON.stringify(res.data))
      //   数据回显(只回显用户名，不会回显密码一般不会回显密码的)
      this.form.username = res.data.username
    },
    async submmit() {
      // 发送修改请求
      const res = await sysUserEdit({ ...this.userInfo, ...this.form })
      // 父组件的内容修改了，子组件的内容数据也要同步更新
      this.propUserInfo.username = this.form.username
      this.propUserInfo.password = this.form.password
      this.$message.success('修改成功')
    },
    // 定义一个方法用于子组件内触发更新
    updataUserInfo(obj) {
      this.userInfo = JSON.parse(JSON.stringify(obj))
      this.form.username = obj.username
    }
  }
}
</script>

<style lang="scss" scoped>
.userlook-box {
  padding: 15px;
  .form {
    padding-top: 50px;
    width: 600px;
    margin: 0 auto;
  }
}
</style>
